export function socket(url, params) {
  return new Promise((resolve, reject) => {
    const ws = new WebSocket(url)
    var reqCode = Math.floor(Math.random() * 10000000000000000)
    ws.onopen = () => {
      console.log('Websocket connection opened.')
      let data = { code: reqCode, data: params, info: { status: 100 } }
      var par = JSON.stringify(data)
      console.log(par)
      ws.send(par)
    }
    ws.onmessage = (event) => {
      console.log('Websocket message received.', event.data)
      var data = JSON.parse(event.data)
      if (data.code == reqCode) {
        resolve(data)
        ws.close()
      }
    }
    ws.onerror = (error) => {
      console.error('Websocket error occurred.', error)
      reject(error)
    }
    ws.onclose = () => {
      console.log('Websocket connection closed.')
    }
  })
}
export class websocket {
  constructor(url, options = {}) {
    this.ws = new WebSocket(url, options)
    this.ws.onopen = () => {
      console.log('Websocket connection opened.')
    }
    this.ws.onerror = (error) => {
      console.error('Websocket error occurred.', error)
    }
    this.ws.onclose = () => {
      console.log('Websocket connection closed.')
    }
  }
  send(params) {
    return new Promise((resolve) => {
      if (this.ws.readyState === WebSocket.OPEN) {
        this.ws.send(params)
      }
      this.ws.onmessage = (event) => {
        resolve(JSON.parse(event.data))
      }
    })
  }
  close() {
    this.ws.close()
  }
}
